﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectManagement.Domain.Services;
using ProjectManagement.Domain.AutoMappings;
using NHibernate.Linq;
using ProjectManagement.Domain.Entities;
using System.Web.Helpers;
using ProjectManagement.Web.Infrastructure;
using System.Web.Security;

namespace ProjectManagement.Web.Controllers
{
	//系统管理
    public class SysManageController : Controller
    {
		private static UserService _userService;
		private static ProvienceService _provicenceService;
		private static CityService _cityService;
		private static RoleService _roleService;
		private static UserRoleService _userRoleService;

		public SysManageController(UserService userService,ProvienceService proService,CityService cityService,RoleService roleService,UserRoleService userRoleService)
		{
			_userService = userService;
			_provicenceService = proService;
			_cityService = cityService;
			_roleService = roleService;
			_userRoleService = userRoleService;
		}
        //
        // GET: /SysManage/

        public ActionResult Index()
        {
            return View();
        }
		//用户列表
		[Permission(Roles = "系统管理员")]
		public ActionResult UserList(int pageIndex=1)
		{
			int pageSize = 15;
			int totalCount = _userService.QueryAll().Count();
			int pageCount = (totalCount / pageSize) + 1;
			ViewBag.TotalCount = totalCount;
			ViewBag.PageIndex = pageIndex;
			ViewBag.PageCount = pageCount;
			var users = _userService.QueryAll()
				.OrderByDescending(u => u.ID)
				.Skip((pageIndex-1)*pageSize)
				.Take(pageSize).ToList();
			return View(users);
		}
		//根据用户名或者真实姓名查询
		[HttpPost]
		public ActionResult UserList(FormCollection form)
		{
			string names = form["name"].ToString();
			string realnames = form["realname"].ToString();
			var users = _userService.QueryAll();
			return View(_userService.QueryUser(users, names, realnames));
		}
		//添加用户
		public ViewResult EditUsers(int Id)
		{
			return View(_userService.Get(Id));
		}
		[HttpPost]
		public ActionResult EditUsers(User user,HttpPostedFileBase image)
		{
			if (ModelState.IsValid)
			{
				if(user.ID==0&&_userService.CheckUserName(user.UserName))
				{
					ModelState.AddModelError("","用户名已存在！");
					return View(user);
				}
				else
				{
					string filename="";
					//图片处理
					if (image != null)
					{
						filename = System.IO.Path.GetFileName(image.FileName);
						string physicalpath = Server.MapPath("~/UpLoad/" + filename);
						image.SaveAs(physicalpath);
						user.ImageUrl = ("/UpLoad/" + filename);
					}
					else
					{
						user.ImageUrl = null;
					}
					user.RegisterTime = DateTime.Now;
					user.Allowed = true;
					_userService.SaveOrUpdate(user);
					TempData["Message"] = "保存成功！";
					return RedirectToAction("UserList");
				}
			}
			else
			{
				return View(user);
			}
		}

		public ViewResult AddUsers()
		{
			return View("EditUsers", new User());
		}

		public ViewResult UserDetails(int Id)
		{
			var user = _userService.Get(Id);
			var userRoleList = _userRoleService.AllRoleUserId();
			//当前用户角色信息
			if (userRoleList.Contains(Id))
			{
				var roleId = _userRoleService.GetRoleId(Id);
				ViewBag.RoleName = _roleService.GetRoleById(roleId).Name;
			}
			else
			{
				ViewBag.RoleName = "暂无角色";
			}
			return View(user);
		}
		//前台ajax请求,返回某省下面的市区
		[HttpPost]
		public JsonResult GetSelectedList(string id)
		{
			int sid = int.Parse(id);
			List<Object> list = new List<Object>();
			var cities = _cityService.QueryCityByProId(sid);
			foreach (var item in cities)
			{
				list.Add(new { 
					ID=item.ID,
					Name=item.Name
				});
			}
			return Json(list,JsonRequestBehavior.AllowGet);
		}

		public ActionResult DeleteUsers(int Id)
		{
			try
			{
				var user = _userService.Get(Id);
				_userService.Remove(user);
				TempData["Message"] = "删除成功";
				return RedirectToAction("UserList");
			}
			catch (Exception)
			{
				TempData["Message"] = "删除失败";
				return RedirectToAction("UserList");
			}
		}

		public ActionResult GiveRole(int uid)
		{
			var userRoleList = _userRoleService.AllRoleUserId();
			UserRole userRole = new UserRole();
			//当前用户角色信息
			if (userRoleList.Contains(uid))
			{
				var roleId = _userRoleService.GetRoleId(uid);
				ViewBag.RoleName = _roleService.GetRoleById(roleId).Name;
				userRole = _userRoleService.GetUserRoleByUserId(uid);
			}
			else
			{
				ViewBag.RoleName = "暂无角色";
				userRole = new UserRole
				{
					ID = 0,
					RoleID = 0,
					UserID = uid
				};
			}
			//角色列表
			var rolelist = _roleService.QueryAll();
			var selectlist = new List<SelectListItem>();
			selectlist.Add(new SelectListItem { Text = "请选择", Value = "" });
			foreach (var item in rolelist)
			{
				selectlist.Add(new SelectListItem
				{
					Text = item.Name,
					Value = item.ID.ToString()
				});
			}
			ViewBag.list = selectlist;
			return View(userRole);
		}

		[HttpPost]
		public ActionResult GiveRole(UserRole userRole)
		{
			_userRoleService.SaveOrUpdate(userRole);
			return RedirectToAction("UserList");
		}

		public ActionResult ForbidUser(int Id)
		{
			var user = _userService.Get(Id);
			if (user.Allowed)
			{
				user.Allowed = false;
				TempData["Message"] = "禁用成功";
			}
			else
			{
				user.Allowed = true;
				TempData["Message"] = "启用成功";
			}
			_userService.SaveOrUpdate(user);
			return RedirectToAction("UserList");
		}

		public ActionResult ChangePassword()
		{
			return View();
		}
		[HttpPost]
		public ActionResult ChangePassword(string oldPassword,string newPassword)
		{
			FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
			FormsAuthenticationTicket ticket = id.Ticket;
			int userId = int.Parse(ticket.UserData);
			var currentUser = _userService.Get(userId);
			if (currentUser.Password != oldPassword)
			{
				TempData["Message"] = "原密码不正确";
			}
			else
			{
				currentUser.Password = newPassword;
				_userService.Update(currentUser);
				TempData["Message"] = "修改成功！";
			}
			return View();
		}
	}
}
